package org.sraosha.framework.util;

import org.sraosha.framework.dto.VerificationCode;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Properties;
import java.util.function.Supplier;

/**
 * @ClassName ImgUtil
 * @Description 操作图片的工具
 */
public class ImgUtil {

    private static DefaultKaptcha defaultKaptcha;

    static {

        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        //如果需要生成算法验证码加上一下配置
        properties.put("kaptcha.textproducer.char.string", "1234567890");
        //如果需要去掉干扰线
        properties.put("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        Config config = new Config(properties);
        defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
    }

    /**
     * 生成验证图片(两个数据做计算)
     * @return
     */
    public static VerificationCode createVerificationCode(){
        // 生成文字验证码
        String text = defaultKaptcha.createText();
        // 个位数字相加
        String s1 = text.substring(0, 1);
        String s2 = text.substring(1, 2);
        int calculationResult = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
        // 生成图片验证码
        BufferedImage bufferedImage = defaultKaptcha.createImage(s1 + "+" + s2 + "=?");
        // 转换为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = byteArrayOutputStream.toByteArray();//转换成字节
        String imageBase64 = Base64.encodeBase64String(bytes);//转换成base64串
        imageBase64 = "data:image/jpg;base64," + imageBase64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n

        String uuid = IdUtil.createUUID();
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setImageBase64(imageBase64);
        verificationCode.setUuid(uuid);
        verificationCode.setCalculationResult(calculationResult);
        return verificationCode;
    }

    /**
     * @Description: 探测图片是否存在
     * @Params:
     * @Return:
     */
    private static boolean requireExists(String imgUrl) {
        boolean flag = false;
        URL url = null;
        try {
            url = new URL(imgUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return flag;
        }
        //打开连接
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            return flag;
        }
        //设置请求方式为"HEAD",进行探测
        try {
            conn.setRequestMethod("HEAD");
        } catch (ProtocolException e) {
            e.printStackTrace();
            return flag;
        }

        //超时响应时间为10秒
        conn.setConnectTimeout(10 * 1000);
        //通过输入流获取图片数据
        InputStream is = null;
        try {
            is = conn.getInputStream();
        } catch (IOException e) {
            flag = true;
            //发生错误说明，图片不存在
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


    /**
     * @ClassName ImgUtil
     * @Description 探测是否存在
     */
    public static class Survey extends ImgUtil {

//        private T t;
//        private R r;
//        public C(T t,R r){
//            this.r = r;
//            this.t = t;
//        }

        /**
         * @Description: 返回失效列表
         * @Params:
         * @Return:
         */
        public boolean surveyImg(Supplier<String> lambda) {
            return requireExists(lambda.get());
        }

    }


}
